﻿using Nlnet.Avalonia.Controls;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using MsBox.Avalonia.Enums;
using static System.Environment;
using 畜牧业审核程序国产.Models.ToolsClass;
using System.Threading;

namespace 畜牧业审核程序国产.Models
{
    internal class MyDataFolderOperator
    {
        //需要做到跨平台,使用跨平台的路径操作：
        //使用.NET提供的Environment类来获取用户的桌面路径。
        //使用System.IO.Path类来构建文件夹路径
        #region 通义千问的答案
        //public static string GetOrSetDataFolderPath(string AppName)
        //{
        //    string dataFolder = GetAppDataFolder(AppName);
        //    if (!Directory.Exists(dataFolder))
        //    {
        //        Directory.CreateDirectory(dataFolder);
        //    }
        //    return dataFolder;
        //}

        //private static string GetAppDataFolder(string MyAppName)//数据文件夹
        //{
        //    // 根据操作系统获取数据文件夹路径
        //    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))//保存在"C:\Users\zxk\AppData\Local\ava畜牧业审核程序"这个文件夹下
        //    {
        //        return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), MyAppName);
        //    }
        //    else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        //    {
        //        string homeDir = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        //        return Path.Combine(homeDir, $".local/share/{MyAppName}");
        //    }
        //    else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
        //    {
        //        string homeDir = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        //        return Path.Combine(homeDir, $"Library/Application Support/{MyAppName}");
        //    }
        //    else
        //    {
        //        throw new PlatformNotSupportedException("Unsupported platform.");
        //    }
        //}
        /// <summary>
        /// 返回不同平台的桌面文件夹
        /// </summary>
        /// <returns></returns>
        /// <exception cref="PlatformNotSupportedException"></exception>
        //private static string GetDesktopPathForCurrentPlatform()
        //{
        //    string desktopPath = null;
        //    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        //    {
        //        // Windows 操作系统
        //        desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); //在某些.NET版本中，Environment.GetFolderPath(SpecialFolder.Desktop) 返回的路径可能包含用户当前正在查看的文件夹的路径，而不是直接返回用户的桌面文件夹路径。这意味着它可能返回的是一个相对路径，而不是绝对路径。Environment.GetFolderPath(SpecialFolder.DesktopDirectory) 通常会返回用户的桌面文件夹的完整路径，并且在大多数.NET实现中，它都会返回一个绝对路径。
        //    }
        //    else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        //    {
        //        // Linux 操作系统
        //        desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        //        desktopPath = Path.Combine(desktopPath, "Desktop");
        //    }
        //    else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
        //    {
        //        // macOS 操作系统
        //        desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
        //    }
        //    else
        //    {
        //        throw new PlatformNotSupportedException("Unsupported platform.");
        //    }

        //    return desktopPath;
        //}
        //public static void GetOrSetDataFolderPathOnDesk(string folderName)
        //{
        //string DeskPath = GetDesktopPathForCurrentPlatform();
        //    string DataFolderPathOnDesk = Path.Combine(DeskPath, folderName);
        //    if (!Directory.Exists(DataFolderPathOnDesk))
        //    {
        //        Directory.CreateDirectory(DataFolderPathOnDesk);
        //        Console.WriteLine($"文件夹已创建在：{DataFolderPathOnDesk}");
        //    }
        //    else
        //    {
        //        Console.WriteLine($"文件夹已存在：{DataFolderPathOnDesk}");
        //    }
        //}
        //private void CreateReviewDataFolderOnDesktop()
        //{
        //    string desktopPath = GetDesktopPathForCurrentPlatform();
        //    string reviewDataFolder = Path.Combine(desktopPath, "审核数据资料");

        //    if (!Directory.Exists(reviewDataFolder))
        //    {
        //        Directory.CreateDirectory(reviewDataFolder);
        //        Console.WriteLine($"文件夹已创建在：{reviewDataFolder}");
        //    }
        //    else
        //    {
        //        Console.WriteLine($"文件夹已存在：{reviewDataFolder}");
        //    }
        //}
        #endregion

        #region chatgpt
        //跨平台获取桌面的路径
//#if DEBUG
//        public static string DesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
//#else
//         public static string DesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
//#endif
        public static readonly string DesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
        //跨平台获取桌面上"审核程序文件夹"的路径
        public static readonly string AuditProgramFolderPath = Path.Combine(DesktopPath, "审核程序文件夹");
        public static readonly string DownloadFolderPathInAuditProgramFolder = Path.Combine(AuditProgramFolderPath, "下载的数据");

        public static readonly string AuditOutcomeFolderPathInAuditProgramFolder = Path.Combine(AuditProgramFolderPath, "审核结果");
        public static readonly string LogFolderInAuditProgramFolder = Path.Combine(AuditProgramFolderPath, "日志");
       // public static readonly string LogFolderInAuditProgramFolder = Path.Combine(AuditProgramFolderPath, "日志");
        //确保桌面上建立了审核程序文件夹
        //public static string AuditProgramFolderPath

        /// <summary>
        /// 使用构造函数确保桌面上已经建立了审核程序文件夹
        /// </summary>
        public static void CreateOrCheckAuditProgramFolderExist()
        {
            if (Directory.Exists(AuditProgramFolderPath) == false)
            {
                Directory.CreateDirectory(AuditProgramFolderPath);
                Directory.CreateDirectory(AuditOutcomeFolderPathInAuditProgramFolder);
                Directory.CreateDirectory(DownloadFolderPathInAuditProgramFolder);
                Directory.CreateDirectory(LogFolderInAuditProgramFolder);
               // Directory.CreateDirectory(LogFolderInAuditProgramFolder);

            }
            //分别判断一下各个文件夹是否存在
            else
            {
                if (!Directory.Exists(AuditOutcomeFolderPathInAuditProgramFolder))
                {
                    Directory.CreateDirectory(AuditOutcomeFolderPathInAuditProgramFolder);
                }
                if (!Directory.Exists(DownloadFolderPathInAuditProgramFolder))
                {
                    Directory.CreateDirectory(DownloadFolderPathInAuditProgramFolder);
                }
                if (!Directory.Exists(LogFolderInAuditProgramFolder))
                {
                    Directory.CreateDirectory(LogFolderInAuditProgramFolder);
                }
            }
            //检查一下数据库文件是否存在
            string databaseFileName = "畜牧业数据库.db";
            string targetFilePath = Path.Combine(AuditProgramFolderPath, databaseFileName);
            if (File.Exists(targetFilePath))
            {
                return;
            }
            // 从嵌入资源中提取数据库文件并复制
            using (Stream resourceStream = Assembly.GetExecutingAssembly()
                .GetManifestResourceStream($"畜牧业审核程序国产.Assets.{databaseFileName}"))
            {
                if (resourceStream == null)
                {
                    MyMessagebox.Show("嵌入资源数据库文件未找到。");
                    return;
                }

                using (FileStream fileStream = new FileStream(targetFilePath, FileMode.Create, FileAccess.Write))
                {
                    resourceStream.CopyTo(fileStream);
                    return;
                }
            }

        }
        /// <summary>
        /// 确保已经在
        /// </summary>
        //public static void CreateOrCheckAuditOutcomeFolderExist()
        //{
        //    if (Directory.Exists(AuditProgramFolderPath) == false)
        //    {
        //        Directory.CreateDirectory(AuditProgramFolderPath);
        //        Directory.CreateDirectory(AuditOutcomeFolderPathInAuditProgramFolder);
        //    }
        //    if (Directory.Exists(AuditOutcomeFolderPathInAuditProgramFolder) == false)
        //    {
        //        Directory.CreateDirectory(AuditOutcomeFolderPathInAuditProgramFolder);
        //    }

        //}
        /// <summary>
        /// 通过 Assembly.GetExecutingAssembly().GetManifestResourceStream 提取资源文件夹(assets)里面的
        /// </summary>
        /// <returns></returns>
        public static  bool CopyDBtoDesktopFolder()
        {
            //确保目标文件夹存在
            CreateOrCheckAuditProgramFolderExist();
            string databaseFileName = "畜牧业数据库.db";
            string targetFilePath = Path.Combine(AuditProgramFolderPath, databaseFileName);
            if (File.Exists(targetFilePath))
            {
                return true;
            }
            // 从嵌入资源中提取数据库文件并复制
            using (Stream resourceStream = Assembly.GetExecutingAssembly()
                .GetManifestResourceStream($"畜牧业审核程序国产.Assets.{databaseFileName}"))
            {
                if (resourceStream == null)
                {
                    MyMessagebox.Show("嵌入资源数据库文件未找到。");
                    return false;
                }

                using (FileStream fileStream = new FileStream(targetFilePath, FileMode.Create, FileAccess.Write))
                {
                    resourceStream.CopyTo(fileStream);
                    return true;
                }
            }
        }
        public static void CreateOrResetDownloadFolder()
        {
            if (Directory.Exists(DownloadFolderPathInAuditProgramFolder))
            {
                Directory.Delete(DownloadFolderPathInAuditProgramFolder, true);
            }
            Directory.CreateDirectory(DownloadFolderPathInAuditProgramFolder);
        }

        //public static void CreateOrResetAuditOutcomeFolder()
        //{
        //    if (Directory.Exists(AuditOutcomeFolderPathInAuditProgramFolder) == false)
        //    {
        //        Directory.CreateDirectory(AuditOutcomeFolderPathInAuditProgramFolder);
        //    }
        //}

        public static FuncOutCome UnZip(string ZipsParentFolderPath)
        {
            FuncOutCome unZipOutcome = new FuncOutCome();
            string zipFile = null;



            string[] zipFiles = Directory.GetFiles(ZipsParentFolderPath, "*.zip");//获取的是全路径
            if (zipFiles.Length == 0)
            {
                unZipOutcome.FuncSuccessCode = FuncOutComeCodeType.NullError;
                unZipOutcome.FuncOutComeInfoArgs += "错误:没有压缩包下载下来!" + Environment.NewLine;
                unZipOutcome.Icon = Icon.Error;
                return unZipOutcome;
            }
            else
            {
                try
                {
                    for (int i = 0; i < zipFiles.Length; i++)
                    {
                        zipFile = zipFiles[i];

                        //string extractPath = Path.Combine(folderPath, Path.GetFileNameWithoutExtension(zipFile));
                        ZipFile.ExtractToDirectory(zipFile, ZipsParentFolderPath, true);
                        //Console.WriteLine($"解压 {zipFile} 到 {folderPath} 成功。");
                        Console.WriteLine($"解压时间{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff:ffffff")}");

                    }
                    unZipOutcome.FuncSuccessCode = FuncOutComeCodeType.Success;
                    unZipOutcome.Icon = Icon.Success;
                    return unZipOutcome;
                }
                catch (System.IO.IOException ex)
                {
                    unZipOutcome.FuncSuccessCode = FuncOutComeCodeType.Error;
                    unZipOutcome.FuncOutComeInfoArgs += $"错误:有重复下载的文件。出错的文件为:{zipFile},错误原因为:{ex.Message}";
                    unZipOutcome.Icon = Icon.Error;
                    return unZipOutcome;


                }
                catch (Exception ex)
                {
                    unZipOutcome.FuncSuccessCode = FuncOutComeCodeType.Error;
                    unZipOutcome.FuncOutComeInfoArgs += $"出现错误。出错的文件为:{zipFile},错误原因为:{ex.Message}";
                    unZipOutcome.Icon = Icon.Error;
                    return unZipOutcome;
                }
            }


            //Task.WaitAll(tasks);
        }
#endregion
    }
}
